package com.EE7th.config;

import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.Properties;

@Component
@MapperScan("com.EE7th.dao")
public class MyBatisConfig {

    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);

        // 设置别名包
        factoryBean.setTypeAliasesPackage("com.EE7th.domain");

        // 指定 MyBatis 映射文件的位置
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:com/EE7th/dao/*.xml"));

        // 创建并配置 Configuration 实例
        Configuration configuration = new Configuration();
        configuration.setMapUnderscoreToCamelCase(true); // 开启自动下划线转驼峰命名
        configuration.setCacheEnabled(false); // 根据需要开启或关闭二级缓存

        // 添加 PageHelper 分页插件
        PageInterceptor pageInterceptor = new PageInterceptor();

        Properties props = new Properties();
        props.setProperty("helperDialect", "mysql"); // 数据库类型
        props.setProperty("reasonable", "true"); // 合理化分页参数
        props.setProperty("supportMethodsArguments", "true"); // 支持方法参数传 pageNum, pageSize
        props.setProperty("params", "pageNum=page;pageSize=pageSize"); // 参数映射
        pageInterceptor.setProperties(props);
        configuration.addInterceptor(pageInterceptor);

        factoryBean.setConfiguration(configuration);
        return factoryBean;
    }
}